<?php
namespace app\common\model;
class UserStatus {
    const SESSION_PREFIX = 'onepeter_cms_';
    const SESSION_IS_ADMIN = 'is_admin';
    const SESSION_IS_LOGIN = 'is_login';
    const SESSION_LOGIN_ID = 'login_id';
    const SESSION_LOGIN_USERNAME = 'login_username';

    /******获取状态*******/
    /**
     * 判断现用户是否admin
     * @return bool
     */
    public function isAdmin() {
        return $this->isTrue(UserStatus::SESSION_IS_ADMIN);
    }

    public function isLogin() {
        return $this->isTrue(UserStatus::SESSION_IS_LOGIN);
    }

    /********设置状态**********/
    /**
     * @param bool $bool
     */
    public function login($id,$username,$admin=false) {
        $this->setSession([
            $this::SESSION_IS_LOGIN => true,
            $this::SESSION_IS_ADMIN => $admin,
            $this::SESSION_LOGIN_ID => $id,
            $this::SESSION_LOGIN_USERNAME => $username
        ]);
    }
    public function logout() {
        $this->clearSession();
    }

    public function getLoginID() {
        return $this->get(UserStatus::SESSION_LOGIN_ID);
    }




    /**
     * @param $data array 例如:
     * [
     *  'is_login' => true,
     *  'is_admin' => true,
     * ]
     */
    private function setSession($data) {
        foreach ($data as $key => $val) {
            $this->set($key,$val);
        }
    }

    /**
     * @param $data array null为清除所有，例如：
     * [
     *  'is_login',
     *  'is_admin',
     * ]
     */
    private function clearSession($data = null) {
        if($data === null) {
            session(null,$this::SESSION_PREFIX);
        }else {
            foreach ($data as $key) {
                session($key,null,$this::SESSION_PREFIX);
            }
        }

    }
    private function set($key,$val) {
        session($key,$val,$this::SESSION_PREFIX);
    }
    private function get($key){
        return session($key,'',$this::SESSION_PREFIX);
    }
    private function isTrue($val) {
        if($this->get($val)){
            return true;
        }else {
            return false;
        }
    }
}